<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="定位器编码" prop="locatorCode">
        <el-input v-model="queryParams.locatorCode" placeholder="请输入定位器编码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="运单号" prop="containerCode">
        <el-input v-model="queryParams.containerCode" placeholder="请输入运单号进行搜索" clearable
          @keyup.enter.native="handleQuery" style="width: 200px; " />
      </el-form-item>
      <el-form-item label="绑定状态" prop="bindStatus">
        <el-select v-model="queryParams.bindStatus" placeholder="请选择绑定状态" clearable>
          <el-option label="已绑定" :value="1" />
          <el-option label="未绑定" :value="-1" />
        </el-select>
      </el-form-item>
      <el-form-item label="定位器状态" prop="locatorStatus">
        <el-select v-model="queryParams.locatorStatus" placeholder="请选择定位器状态" clearable>
          <el-option v-for="dict in dict.type.device_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="最后在线时间">
        <el-date-picker v-model="queryParams.lastOnlineTime" style="width: 240px" value-format="yyyy-MM-dd"
          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['locator:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['locator:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['locator:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-close" size="mini" :disabled="unbindDisabled"
          @click="handleUnbind" v-hasPermi="['locator:unbind']">解绑运单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['locator:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['locator:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="locatorList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="定位器编码" align="center" prop="locatorCode" width="150" sortable />
      <el-table-column label="定位器状态" align="center" prop="locatorStatus" width="90">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_status" :value="scope.row.locatorStatus" />
        </template>
      </el-table-column>
      <el-table-column label="电池电量" align="center" prop="batteryLevel" width="150" sortable>
        <template slot-scope="scope">
          <el-progress :percentage="scope.row.batteryLevel"
            :color="getBatteryColor(scope.row.batteryLevel)"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="绑定运单" align="center" prop="containerCode" min-width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.containerCode || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后在线" align="center" prop="lastOnlineTime" width="170" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastOnlineTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)"
            v-hasPermi="['locator:detail']">详情</el-button>
          <el-button
            v-if="scope.row.containerId && scope.row.containerId !== 0 && scope.row.containerId !== -1 && scope.row.containerCode"
            size="mini" type="text" icon="el-icon-close" @click="handleUnbindSingle(scope.row)"
            v-hasPermi="['locator:unbind']">解绑</el-button>
          <el-button
            v-if="!scope.row.containerId || scope.row.containerId === 0 || scope.row.containerId === -1 || !scope.row.containerCode"
            size="mini" type="text" icon="el-icon-link" @click="handleBindWaybill(scope.row)"
            v-hasPermi="['locator:bind']">绑定</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改定位器对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="定位器编码" prop="locatorCode">
              <el-input v-model="form.locatorCode" placeholder="请输入定位器编码" :disabled="form.locatorId != null" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="定位器状态" prop="locatorStatus">
              <el-select v-model="form.locatorStatus" placeholder="请选择定位器状态">
                <el-option label="正常" value="1" />
                <el-option label="离线" value="2" />
                <el-option label="故障" value="3" />
                <el-option label="停用" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上报间隔" prop="reportInterval">
              <el-input-number v-model="form.reportInterval" :min="10" :max="3600" placeholder="上报间隔(秒)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="低电量阈值" prop="lowBatteryThreshold">
              <el-input-number v-model="form.lowBatteryThreshold" :min="0" :max="100" placeholder="低电量阈值(%)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 定位器详情抽屉 -->
    <el-drawer title="定位器详情" :visible.sync="detailOpen" direction="rtl" size="60%">
      <div class="drawer-content" v-if="detailData">
        <!-- 设备基本信息 -->
        <el-card class="box-card" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span>设备基本信息</span>
          </div>
          <el-row>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">定位器编码：</span>
                <span class="value">{{ detailData.locatorCode }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">定位器状态：</span>
                <dict-tag :options="dict.type.device_status" :value="detailData.locatorStatus" />
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 位置信息 -->
        <el-card class="box-card" style="margin-bottom: 20px;"
          v-if="detailData.currentLongitude && detailData.currentLatitude">
          <div slot="header" class="clearfix">
            <span>当前位置信息</span>
          </div>
          <el-row>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">经度：</span>
                <span class="value">{{ detailData.currentLongitude }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">纬度：</span>
                <span class="value">{{ detailData.currentLatitude }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">最后上报：</span>
                <span class="value">{{ parseTime(detailData.lastReportTime) }}</span>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="info-item">
                <span class="label">详细地址：</span>
                <span class="value">{{ detailData.currentAddress || '地址解析中...' }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 运单绑定信息 -->
        <el-card class="box-card" style="margin-bottom: 20px;"
          v-if="detailData.containerId && detailData.containerId !== 0 && detailData.containerId !== -1 && detailData.containerCode">
          <div slot="header" class="clearfix">
            <span>运单绑定信息</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="handleUnbindSingle(detailData)"
              v-hasPermi="['locator:unbind']">解绑运单</el-button>
          </div>
          <el-row>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">运单ID：</span>
                <span class="value">{{ detailData.containerId }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">运单编号：</span>
                <span class="value">{{ detailData.containerCode || '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 定位日志 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>定位日志</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="handleLocationLogs">查看更多</el-button>
          </div>
          <el-table :data="locationLogs" style="width: 100%" max-height="300" v-loading="locationLogsLoading">
            <el-table-column prop="uploadTime" label="定位时间" width="150">
              <template slot-scope="scope">
                {{ parseTime(scope.row.uploadTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
              </template>
            </el-table-column>
            <el-table-column prop="longitude" label="经度" width="100" />
            <el-table-column prop="latitude" label="纬度" width="100" />
            <el-table-column prop="uploadAddress" label="地址" show-overflow-tooltip />
            <el-table-column prop="batteryLevel" label="电量" width="80">
              <template slot-scope="scope">
                {{ scope.row.batteryLevel }}%
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </el-drawer>

    <!-- 绑定运单抽屉 -->
    <el-drawer title="绑定运单" :visible.sync="bindOpen" direction="rtl" size="60%">
      <div class="drawer-content" v-if="bindData">
        <!-- 设备基本信息 -->
        <el-card class="box-card" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span>设备基本信息</span>
          </div>
          <el-row>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">定位器编码：</span>
                <span class="value">{{ bindData.locatorCode }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">定位器状态：</span>
                <dict-tag :options="dict.type.device_status" :value="bindData.locatorStatus" />
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 可绑定运单列表 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>选择要绑定的运单</span>
          </div>
          <el-table :data="availableWaybills" style="width: 100%" max-height="600"
            @current-change="handleWaybillSelection" ref="waybillTable" highlight-current-row>
            <el-table-column type="index" width="55" align="center" label="序号" />
            <el-table-column prop="billNo" label="运单编号" width="120" />
            <el-table-column prop="senderName" label="发货方" width="120" />
            <el-table-column prop="addressA" label="发货地址" show-overflow-tooltip />
            <el-table-column prop="receiverName" label="收货方" width="120" />
            <el-table-column prop="addressB" label="收货地址" show-overflow-tooltip />
            <el-table-column prop="billStatus" label="运单状态" width="80" align="center">
              <template slot-scope="scope">
                <el-tag type="warning">待发货</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="goodsName" label="货物名称" width="100" />
            <el-table-column prop="goodsWeight" label="货物重量(kg)" width="100" align="right" />
          </el-table>

          <div style="margin-top: 20px; text-align: center;">
            <el-button @click="bindOpen = false">取 消</el-button>
            <el-button type="primary" @click="confirmBind" :disabled="!selectedWaybill">确认绑定</el-button>
          </div>
        </el-card>
      </div>
    </el-drawer>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            仅允许导入xls、xlsx格式文件。
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate">下载模板</el-link>
          </div>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLocator, getLocator, delLocator, addLocator, updateLocator, exportLocator, unbindShipment, getLocationLogs } from "@/api/pack/locator";
import { listWayBill } from "@/api/system/waybill";
import { getToken } from "@/utils/auth";
import request from '@/utils/request';

export default {
  name: "Locator",
  dicts: ['device_status', 'usage_status'],
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 解绑按钮禁用
      unbindDisabled: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 定位器表格数据
      locatorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情抽屉
      detailOpen: false,
      // 详情数据
      detailData: null,
      // 定位日志数据
      locationLogs: [],
      // 定位日志加载状态
      locationLogsLoading: false,
      // 是否显示绑定抽屉
      bindOpen: false,
      // 绑定数据
      bindData: null,
      // 可绑定的运单列表
      availableWaybills: [],
      // 选中的运单
      selectedWaybill: null,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        locatorCode: null,
        containerCode: null,
        bindStatus: null,
        locatorStatus: null,
        lastOnlineTime: [],
        // 默认按最后在线时间倒序排序
        orderByColumn: 'lastOnlineTime',
        isAsc: 'desc'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        locatorCode: [
          { required: true, message: "定位器编码不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "定位器编码长度必须介于 1 和 50 之间", trigger: "blur" }
        ],

        locatorStatus: [
          { required: true, message: "定位器状态不能为空", trigger: "change" }
        ],
        reportInterval: [
          { required: true, message: "上报间隔不能为空", trigger: "blur" }
        ],
        lowBatteryThreshold: [
          { required: true, message: "低电量阈值不能为空", trigger: "blur" }
        ]
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/locator/importData"
      }
    };
  },
  created () {
    this.getList();
  },
  methods: {
    /** 查询定位器列表 */
    getList () {
      this.loading = true;
      console.log('定位器列表查询参数:', this.queryParams);
      listLocator(this.queryParams).then(response => {
        this.locatorList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log('定位器列表查询结果:', response);
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        locatorId: null,
        locatorCode: null,
        locatorStatus: "1",
        deviceModel: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.queryParams.lastOnlineTime = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.locatorId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      // 检查是否有绑定运单的设备用于解绑按钮状态
      this.unbindDisabled = !selection.some(item => item.containerId && item.containerId !== 0 && item.containerId !== -1 && item.containerCode);
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加定位器";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const locatorId = row.locatorId || this.ids;
      getLocator(locatorId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改定位器";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.locatorId != null) {
            updateLocator(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLocator(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const locatorIds = row.locatorId || this.ids;
      this.$modal.confirm('是否确认删除定位器编号为"' + locatorIds + '"的数据项？').then(function () {
        return delLocator(locatorIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 解绑运单操作 */
    handleUnbind () {
      const locatorIds = this.ids;
      this.$modal.confirm('是否确认解绑选中定位器的运单？').then(function () {
        return unbindShipment(locatorIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("解绑成功");
      }).catch(() => { });
    },
    /** 单个解绑运单操作 */
    handleUnbindSingle (row) {
      this.$modal.confirm('是否确认解绑该定位器的运单？解绑后定位器将不再与此运单关联。').then(function () {
        return unbindShipment([row.locatorId]); // 将单个ID包装成数组
      }).then(() => {
        this.getList();
        if (this.detailOpen) {
          this.handleDetail(row);
        }
        this.$modal.msgSuccess("解绑成功");
      }).catch(() => { });
    },
    /** 查看详情 */
    handleDetail (row) {
      getLocator(row.locatorId).then(response => {
        this.detailData = response.data;
        this.detailOpen = true;
        // 加载定位日志
        this.loadLocationLogs(row.locatorId);
      });
    },
    /** 加载定位日志 */
    loadLocationLogs (locatorId) {
      this.locationLogsLoading = true;
      const params = {
        locatorId: locatorId,
        pageNum: 1,
        pageSize: 10
      };

      // 如果定位器绑定了运单，也添加运单ID作为查询条件
      if (this.detailData && this.detailData.containerId && this.detailData.containerId !== 0 && this.detailData.containerId !== -1) {
        params.containerId = this.detailData.containerId;
      }

      console.log('定位日志查询参数:', params);

      getLocationLogs(params).then(response => {
        this.locationLogs = response.rows || [];
        console.log('定位日志查询结果:', response);
      }).catch(error => {
        console.error('加载定位日志失败:', error);
        this.$modal.msgError('加载定位日志失败');
      }).finally(() => {
        this.locationLogsLoading = false;
      });
    },
    /** 查看更多定位日志 */
    handleLocationLogs () {
      // 跳转到定位日志详情页面
      this.$router.push({
        path: '/locator/detail',
        query: { locatorId: this.detailData.locatorId }
      });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('locator/export', {
        ...this.queryParams
      }, `locator_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport () {
      this.upload.title = "定位器导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate () {
      this.download('locator/importTemplate', {}, `locator_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs.upload.submit();
    },
    /** 获取电池颜色 */
    getBatteryColor (level) {
      if (level > 50) return '#67c23a';
      if (level > 20) return '#e6a23c';
      return '#f56c6c';
    },
    /** 绑定运单 */
    handleBindWaybill (row) {
      this.bindData = row;
      this.bindOpen = true;
      this.selectedWaybill = null;
      // 清空表格当前行选择
      this.$nextTick(() => {
        this.$refs.waybillTable && this.$refs.waybillTable.setCurrentRow();
      });
      // 加载可绑定的运单列表
      this.loadAvailableWaybills();
    },
    /** 加载可绑定的运单列表 */
    loadAvailableWaybills () {
      const queryParams = {
        billStatus: '待发货', // 待发货状态
        locatorId: -1, // locatorId为空
        locatorCode: "-1", // locatorCode为空
        pageNum: 1,
        pageSize: -1 // 获取更多数据
      };

      listWayBill(queryParams).then(response => {
        // 过滤出locatorId和locatorCode都为空的运单
        this.availableWaybills = (response.rows || []).filter(item =>
          (!item.locatorId || item.locatorId === 0) &&
          (!item.locatorCode || item.locatorCode === '')
        );
      }).catch(error => {
        this.$modal.msgError("加载运单列表失败");
        console.error(error);
      });
    },
    /** 运单选择变化（单选模式） */
    handleWaybillSelection (currentRow) {
      this.selectedWaybill = currentRow;
    },
    /** 确认绑定 */
    confirmBind () {
      if (!this.selectedWaybill) {
        this.$modal.msgError("请选择要绑定的运单");
        return;
      }

      request({
        url: `/pack/locator/${this.bindData.locatorId}/bind-waybill`,
        method: 'put',
        params: {
          waybillId: this.selectedWaybill.id,
          waybillNo: this.selectedWaybill.billNo
        }
      }).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("绑定成功");
          this.bindOpen = false; // 关闭抽屉
          this.getList(); // 刷新列表
          this.selectedWaybill = null; // 清空选择
        } else {
          this.$modal.msgError(response.msg || "绑定失败");
        }
      }).catch(error => {
        this.$modal.msgError("绑定异常");
        console.error(error);
      });
    }
  }
};
</script>

<style scoped>
.drawer-content {
  padding: 20px;
}

.info-item {
  margin-bottom: 10px;
}

.info-item .label {
  font-weight: bold;
  color: #606266;
}

.info-item .value {
  color: #303133;
}

.box-card {
  margin-bottom: 20px;
}
</style>
